from django.shortcuts import render
from rest_framework.generics import GenericAPIView
from libs.captcha.captcha.captcha import captcha
# from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from django.http import HttpResponse
from rest_framework.views import APIView
from . import constants
from .serializers import RegisterSmscodeserializers
from random import randint
from rest_framework.response import Response
from rest_framework import status
from libs.yuntongxun.sms import CCP
# Create your views here.

class RegisterImagecodeView(APIView):
    def get(self, request,image_code_id):
        # 创建图片和验证码
        # text,image = captcha.generate_captcha()
        text,image = captcha.generate_captcha()
        # 通过redis进行保存验证码
        redis_conn = get_redis_connection('code')
        redis_conn.setex('img_%s' % image_code_id,constants.IMAGE_EXPIRE_TIME,text)
        # 将图片返回
        # 注意,图片是二进制,我们通过HttpResponse返回
        return HttpResponse(image, content_type='image/jpeg')


class RegisterSmscodeView(GenericAPIView):


    serializer_class = RegisterSmscodeserializers

    def get(self,request,mobile):
        #获取手机号，验证码
        #request.query_params就是request.GET
        params=request.query_params
        #对用户输入的校验
        #1调取方法
        serializer=self.get_serializer(data=params)
        serializer.is_valid(raise_exception=True)
        #生成短信
        sms_code='%06d'%randint(0,999999)

        #链接数据库code
        redis_conn=get_redis_connection('code')

        #3.2需要先判断，用户有没有给用户发送过
        flag = redis_conn.get('sms_flag_%s'%mobile)
        if flag:
            return Response(status=status.HTTP_429_TOO_MANY_REQUESTS)


        # 将短信记录在redis中
        redis_conn.setex('sms_%s'%mobile,60*5,sms_code)

        #记录一个标记
        redis_conn.setex('sms_flag_%s'%mobile,60,1)

        #手机发送短信
        ccp=CCP

        #发送
        ccp.send_template_sms(mobile,[sms_code,5],1)

        return Response({'message':'ok'})







